package com.neusoft.tijian.service.impl;

import com.neusoft.tijian.dto.OrdersQueryDto;
import com.neusoft.tijian.config.PageResult;
import com.neusoft.tijian.mapper.OrdersMapper;
import com.neusoft.tijian.po.Orders;
import com.neusoft.tijian.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class OrdersServiceImpl implements IOrdersService {

    @Autowired
    private OrdersMapper ordersMapper;



    @Override
    public PageResult<Orders> listOrders(OrdersQueryDto query) {
        // 计算分页起始位置
        int start = (query.getPageNum() - 1) * query.getPageSize();
        // 查询分页数据
        List<Orders> list = ordersMapper.listOrders(query, start);
        // 查询总条数
        Integer total = ordersMapper.countOrders(query);
        // 返回分页结果
        return new PageResult<>(list, total, query.getPageNum(), query.getPageSize());
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public Integer updateOrdersState(Integer orderId, Integer state) {
        return ordersMapper.updateOrdersState(orderId, state);
    }

    @Override
    public Integer saveOrders(Orders orders) {
        // 可选：添加业务校验（如判断用户是否已预约该日期、医院/套餐是否存在等）
        if (orders.getUserId() == null || orders.getOrderDate() == null) {
            return 0;  // 必要参数为空，返回失败
        }

        // 调用Mapper接口插入订单
        return ordersMapper.saveOrders(orders);
    }


    // -------------------------- 实现用户端方法 --------------------------
    @Override
    public PageResult<Orders> listUserOrders(String userId, Integer pageNum, Integer pageSize) {
        // 1. 参数校验：避免空指针/无效参数
        if (userId == null || userId.trim().isEmpty()) {
            return new PageResult<>(Collections.emptyList(), 0, 1, pageSize); // 返回空列表
        }
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 2. 计算分页起始位置（与医生端分页逻辑一致）
        int start = (pageNum - 1) * pageSize;

        // 3. 调用Mapper查询数据
        List<Orders> ordersList = ordersMapper.listUserOrders(userId.trim(), start, pageSize);
        Integer total = ordersMapper.countUserOrders(userId.trim());

        // 4. 返回分页结果（复用现有PageResult类）
        return new PageResult<>(ordersList, total, pageNum, pageSize);
    }

    @Override
    public Integer cancelUserOrder(Integer orderId) {
        // 1. 参数校验：预约ID无效直接返回失败
        if (orderId == null || orderId < 1) {
            return 0;
        }
        // 2. 调用Mapper取消预约（更新state为3）
        return ordersMapper.cancelUserOrder(orderId);
    }
}